package com.headwind.autoconfigure.formatter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/2
 * @description : Formatter 接口的json格式实现
 */
public class JsonFormatter implements Formatter {

    /**
     * 定义Json解析对象实现类
     */
    private final ObjectMapper objectMapper;

    /**
     * 无参构造
     */
    public JsonFormatter() {
        this(new ObjectMapper());
    }

    /**
     * 构造函数
     *
     * @param objectMapper Json解析对象实现类
     */
    public JsonFormatter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String format(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            // 解析失败返回非法参数异常
            throw new IllegalArgumentException(e);
        }
    }
}
